﻿using famails.bus;
using FAMailUtils;
using FAMailUtils.Data.DAO;
using FAMailUtils.Data.DTO;
using FAMailUtils.Payment;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace OnlineBusinesses.Areas.CustomerAdmin
{
    public partial class Payment : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                UserLoginDTO user = ((CustomerAdmin.AdminCustomer_Master)this.Master).getUserLogin();
                lblClientName.Text = user.Client.ClientName;
                lblEmail.Text = user.Client.Email;
                lblAddress.Text = user.Client.Address;
                lblPhone.Text = user.Client.Phone;
                lblCardNo.Text = user.Client.cardId;


                ClientBUS clientbus = new ClientBUS();
                DataTable dtClient = new DataTable();
                dtClient = clientbus.GetByID(user.Client.UserID);
                PackageBUS pkgBus = new PackageBUS();
                PackageTimeBUS timeBus = new PackageTimeBUS();
                ClientRegisterBUS clientRegister = new ClientRegisterBUS();
                int clientId = Convert.ToInt32(dtClient.Rows[0]["clientId"].ToString());
                //DataTable dtClientRegister = clientRegister.GetbyID(registerId);
                DataTable dtClientRegister = clientRegister.GetUnPaymentByClientID(clientId);
                if (dtClientRegister != null && dtClientRegister.Rows.Count > 0)
                {
                    int registerId = Convert.ToInt32(dtClientRegister.Rows[0]["registerId"].ToString());
                    string packageid = dtClientRegister.Rows[0]["packageId"].ToString();
                    DataTable dtpackage = pkgBus.GetById(Convert.ToInt32(packageid));
                    DataTable time = timeBus.GetByID((int)dtClientRegister.Rows[0]["packageTimeId"]);
                    lblFee.Text = "" + dtClientRegister.Rows[0]["totalfee"] + "USD";
                    lblPackageName.Text = dtpackage.Rows[0]["PackageName"] + "";
                    lblMonthCount.Text = time.Rows[0]["monthCount"] + " tháng";
                    lblExpireDate.Text = Convert.ToDateTime(dtClientRegister.Rows[0]["to"] + "").ToString("dd/MM/yyyy");
                    lblTransactionCode.Text = dtClientRegister.Rows[0]["TransactionCode"] + "";
                    hdfRegisterID.Value = registerId + "";
                }
            }
        }

        private OnePayHandling oh = new OnePayHandling();
        protected void btnThanhThoan_Click(object sender, EventArgs e)
        {
            try
            {
                if (!cbDieuKhoan.Checked) { lblStatus.Text = "Vui lòng xác nhận sau khi bạn đã đọc các điều khoản ở trên."; lblStatus.Visible = true; return; }
                if (!rdbATM.Checked && !rdbTheQT.Checked) { lblStatus.Text = "Vui lòng chọn thẻ thanh toán."; lblStatus.Visible = true; return; }
                UserLoginDTO user = ((CustomerAdmin.AdminCustomer_Master)this.Master).getUserLogin();
                OnePayRedirect opr = new OnePayRedirect();
                string againLink = "inland";
                if (rdbTheQT.Checked)
                    againLink = "international";

                float exchangeRate = OnePaySetting.GetExchangeRate(); // Tỷ giá VND/USD
                float amount = 0;
                double paymentamount = 0;
                float.TryParse(lblFee.Text.Replace("USD", ""), out amount);
                float vat = amount * 10 / 100; // Thuế VA

                paymentamount = (amount + vat) * exchangeRate; // Tổng tiền (chưa làm tròn)
                paymentamount = (Math.Round(paymentamount / 1000) * 1000 * 100);
                opr.Amount = paymentamount.ToString("###"); // Tổng tiền (VND)

                opr.OrderInfo = lblTransactionCode.Text; // Mã đơn hàng

                opr.TicketNo = Request.UserHostAddress; // IP

                opr.MerchTxnRef = Path.GetRandomFileName();

                opr.AgainLink = Request.Url.AbsoluteUri;

                opr.CustomerEmail = Session["EmailLogin"]+"";

                opr.Title = "Thanh toán trực tuyến bằng thẻ VISA, MASTER, JCB";
                if (rdbTheQT.Checked)
                    opr.Title = "Thanh toán trực tuyến bằng thẻ ATM 23 ngân hàng";

                PaymentDAO dao = new PaymentDAO();
                PaymentDTO dto = new PaymentDTO();
                dto.Amount = amount;
                dto.PaymentAmount = Convert.ToDecimal(paymentamount);
                dto.ExchangeRate = exchangeRate;
                dto.OrderInfo = opr.OrderInfo;
                dto.TicketNo = opr.TicketNo;
                dto.MerchTxnRef = opr.MerchTxnRef;
                dto.AgainLink = opr.AgainLink;
                dto.Title = opr.Title;
                dto.receiverId = user.Client.UserID + "-" + hdfRegisterID.Value;
                dto.UserID = user.Client.UserID;
                dto.RegisterID = hdfRegisterID.Value;
                object paymentid = dao.Payment(dto);


                string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/";
                string returnUrl = baseUrl + "Areas/CustomerAdmin/Confirmation.aspx?paymentType=" + againLink + "&receiverId=" + user.Client.UserID + "-" + hdfRegisterID.Value + "-" + paymentid;
                string ResponeUrl = oh.Redirect(opr, rdbATM.Checked, returnUrl);
                Common.logs(Request.RawUrl + "-" + Common.GetCurrentMethod() + "-ResponeUrl:" + ResponeUrl, null, Common.logType.info);
                Common.logs(Request.RawUrl + "-" + Common.GetCurrentMethod() + "-ReturnUrl:" + returnUrl, null, Common.logType.info);
                Response.Redirect(ResponeUrl, true);
            }
            catch (Exception ex)
            {
                Common.logs(Request.RawUrl + "-" + Common.GetCurrentMethod(), ex, Common.logType.error);
                lblStatus.Text = ex.Message;
            }
        }
    }
}